package com.github.codemperor.core.ajax;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

public class Ajax {

    private Ajax() {
    }

    public static Ajax build() {
        return new Ajax().init();
    }

    private RestTemplate restTemplate;
    private HttpHeaders httpHeaders;

    private Ajax init() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(10000);
        factory.setReadTimeout(10000);
        restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new RestErrorException());
        httpHeaders = new HttpHeaders();
        return this;
    }

    public Ajax addHeaders(String key, String value) {
        httpHeaders.add(key, value);
        return this;
    }

    /**
     * post
     *
     * @return
     */
    public ResponseEntity<String> postWithFormData(String url, Object request) {
        addHeaders("Content-Type", "application/x-www-form-urlencoded");
        return restTemplate.postForEntity(url, new HttpEntity<>(request, httpHeaders), String.class);
    }

    /**
     * post
     *
     * @return
     */
    public ResponseEntity<Object> postWithContentTypeJson(String url, Object request) {
        httpHeaders.add("Content-Type", "application/json");
        return restTemplate.postForEntity(url, new HttpEntity<>(request, httpHeaders), Object.class);
    }

    /**
     * get
     *
     * @return
     */
    public ResponseEntity<Object> get(String url) {
        httpHeaders.add("Content-Type", "application/json");
        return restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null, httpHeaders), Object.class);
    }

}
